import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable, of, throwError } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';
import { environment } from '../../environments/environment';
import {
  RepairRequest, WorkflowInstance, WorkflowStep, User, UserRole,
  RepairStatus, WorkflowStatus, StepStatus, Device, ExternalVendor,
  StartWorkflowRequest, DecisionRequest, ExternalVendorRequest,
  InternalRepairRequest, RepairDetailsRequest, ApprovalRequest,
  WorkflowActionResponse, PendingTask, RepairPriority
} from '../models/repair-workflow.model';

@Injectable({
  providedIn: 'root'
})
export class RepairWorkflowService {
  private apiUrl = environment.apiUrl;
  private currentUserSubject = new BehaviorSubject<User | null>(null);
  private workflowInstancesSubject = new BehaviorSubject<WorkflowInstance[]>([]);

  public currentUser$ = this.currentUserSubject.asObservable();
  public workflowInstances$ = this.workflowInstancesSubject.asObservable();

  private httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

  constructor(private http: HttpClient) {
    this.initializeMockUser();
  }

  private initializeMockUser(): void {
    // 模拟当前登录用户（实际应用中从认证服务获取）
    const mockUser: User = {
      id: 1,
      username: 'technician1',
      fullName: '张三',
      name: '张三',
      email: 'zhangsan@company.com',
      phone: '13888888888',
      role: UserRole.TECHNICIAN,
      department: '维修部',
      createdAt: new Date(),
      isActive: true
    };
    this.currentUserSubject.next(mockUser);
  }

  // 获取当前用户
  getCurrentUser(): User | null {
    return this.currentUserSubject.value;
  }

  // 切换用户角色（用于演示）
  switchUserRole(role: UserRole): void {
    const currentUser = this.getCurrentUser();
    if (currentUser) {
      const updatedUser: User = {
        ...currentUser,
        role,
        fullName: role === UserRole.ADMIN ? '李四' : '张三',
        name: role === UserRole.ADMIN ? '李四' : '张三',
        username: role === UserRole.ADMIN ? 'admin1' : 'technician1',
        id: role === UserRole.ADMIN ? 2 : 1
      };
      this.currentUserSubject.next(updatedUser);
    }
  }

  // API Methods

  // 获取所有设备
  getDevices(): Observable<Device[]> {
    return this.http.get<Device[]>(`${this.apiUrl}/devices`).pipe(
      catchError(this.handleError<Device[]>('getDevices', []))
    );
  }

  // 获取设备详情
  getDevice(id: number): Observable<Device> {
    return this.http.get<Device>(`${this.apiUrl}/devices/${id}`).pipe(
      catchError(this.handleError<Device>('getDevice'))
    );
  }

  // 获取所有用户
  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(`${this.apiUrl}/users`).pipe(
      catchError(this.handleError<User[]>('getUsers', []))
    );
  }

  // 获取外部厂商
  getExternalVendors(): Observable<ExternalVendor[]> {
    return this.http.get<ExternalVendor[]>(`${this.apiUrl}/externalvendors`).pipe(
      catchError(this.handleError<ExternalVendor[]>('getExternalVendors', []))
    );
  }

  // 创建维修申请
  createRepairRequest(request: Partial<RepairRequest>): Observable<RepairRequest> {
    return this.http.post<RepairRequest>(`${this.apiUrl}/repairrequests`, request, this.httpOptions).pipe(
      catchError(this.handleError<RepairRequest>('createRepairRequest'))
    );
  }

  // 获取维修申请
  getRepairRequests(): Observable<RepairRequest[]> {
    return this.http.get<RepairRequest[]>(`${this.apiUrl}/repairrequests`).pipe(
      catchError(this.handleError<RepairRequest[]>('getRepairRequests', []))
    );
  }

  // 获取维修申请详情
  getRepairRequest(id: number): Observable<RepairRequest> {
    return this.http.get<RepairRequest>(`${this.apiUrl}/repairrequests/${id}`).pipe(
      catchError(this.handleError<RepairRequest>('getRepairRequest'))
    );
  }

  // 启动工作流
  startWorkflow(repairRequestId: number): Observable<WorkflowActionResponse> {
    const currentUser = this.getCurrentUser();
    const request: StartWorkflowRequest = {
      repairRequestId,
      currentUser: currentUser?.fullName || 'Unknown'
    };

    return this.http.post<WorkflowActionResponse>(`${this.apiUrl}/repairrequests/${repairRequestId}/start-workflow`, request, this.httpOptions).pipe(
      catchError(this.handleError<WorkflowActionResponse>('startWorkflow'))
    );
  }

  // 工作流步骤操作

  // 做决策（是否委托外部维修）
  makeDecision(workflowInstanceId: number, isExternalRepair: boolean): Observable<WorkflowActionResponse> {
    const request: DecisionRequest = {
      workflowInstanceId,
      isExternalRepair
    };

    return this.http.post<WorkflowActionResponse>(`${this.apiUrl}/workflow/decision`, request, this.httpOptions).pipe(
      catchError(this.handleError<WorkflowActionResponse>('makeDecision'))
    );
  }

  // 提交外部厂商信息
  submitExternalVendor(workflowInstanceId: number, externalVendorId: number): Observable<WorkflowActionResponse> {
    const request: ExternalVendorRequest = {
      workflowInstanceId,
      externalVendorId
    };

    return this.http.post<WorkflowActionResponse>(`${this.apiUrl}/workflow/external-vendor`, request, this.httpOptions).pipe(
      catchError(this.handleError<WorkflowActionResponse>('submitExternalVendor'))
    );
  }

  // 提交内部维修工单
  submitInternalRepair(workflowInstanceId: number): Observable<WorkflowActionResponse> {
    const request: InternalRepairRequest = {
      workflowInstanceId
    };

    return this.http.post<WorkflowActionResponse>(`${this.apiUrl}/workflow/internal-repair`, request, this.httpOptions).pipe(
      catchError(this.handleError<WorkflowActionResponse>('submitInternalRepair'))
    );
  }

  // 提交维修详情
  submitRepairDetails(workflowInstanceId: number, repairContent: string, repairHours: number, repairCost: number, repairNotes?: string): Observable<WorkflowActionResponse> {
    const request: RepairDetailsRequest = {
      workflowInstanceId,
      repairContent,
      repairHours,
      repairCost,
      repairNotes
    };

    return this.http.post<WorkflowActionResponse>(`${this.apiUrl}/workflow/repair-details`, request, this.httpOptions).pipe(
      catchError(this.handleError<WorkflowActionResponse>('submitRepairDetails'))
    );
  }

  // 提交审批
  submitApproval(workflowInstanceId: number, isApproved: boolean, approvalNotes?: string): Observable<WorkflowActionResponse> {
    const currentUser = this.getCurrentUser();
    const request: ApprovalRequest = {
      workflowInstanceId,
      isApproved,
      approvalNotes,
      approvedBy: currentUser?.fullName || 'Unknown'
    };

    return this.http.post<WorkflowActionResponse>(`${this.apiUrl}/workflow/approval`, request, this.httpOptions).pipe(
      catchError(this.handleError<WorkflowActionResponse>('submitApproval'))
    );
  }

  // 获取工作流实例
  getWorkflowInstance(id: number): Observable<WorkflowInstance> {
    return this.http.get<WorkflowInstance>(`${this.apiUrl}/workflow/instance/${id}`).pipe(
      catchError(this.handleError<WorkflowInstance>('getWorkflowInstance'))
    );
  }

  // 获取所有工作流实例
  getWorkflowInstances(status?: string, currentStep?: string): Observable<WorkflowInstance[]> {
    let url = `${this.apiUrl}/workflow/instances`;
    const params = new URLSearchParams();
    
    if (status) params.append('status', status);
    if (currentStep) params.append('currentStep', currentStep);
    
    if (params.toString()) {
      url += '?' + params.toString();
    }

    return this.http.get<WorkflowInstance[]>(url).pipe(
      tap(instances => this.workflowInstancesSubject.next(instances)),
      catchError(this.handleError<WorkflowInstance[]>('getWorkflowInstances', []))
    );
  }

  // 获取待办任务
  getPendingTasks(userRole?: string): Observable<PendingTask[]> {
    let url = `${this.apiUrl}/workflow/pending-tasks`;
    if (userRole) {
      url += `?userRole=${userRole}`;
    }

    return this.http.get<PendingTask[]>(url).pipe(
      catchError(this.handleError<PendingTask[]>('getPendingTasks', []))
    );
  }

  // 获取当前用户的待办任务
  getCurrentUserTasks(): Observable<PendingTask[]> {
    const currentUser = this.getCurrentUser();
    if (!currentUser) {
      return of([]);
    }

    const userRole = currentUser.role === UserRole.ADMIN ? 'admin' : 'technician';
    return this.getPendingTasks(userRole);
  }

  // 错误处理
  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(`${operation} failed: ${error.message}`);
      
      // 返回空结果让应用继续运行
      return of(result as T);
    };
  }

  // 辅助方法
  getRepairPriorityText(priority: RepairPriority): string {
    switch (priority) {
      case RepairPriority.LOW: return '低';
      case RepairPriority.MEDIUM: return '中';
      case RepairPriority.HIGH: return '高';
      case RepairPriority.CRITICAL: return '紧急';
      default: return '未知';
    }
  }

  getRepairStatusText(status: RepairStatus): string {
    switch (status) {
      case RepairStatus.PENDING: return '待处理';
      case RepairStatus.DECISION_PENDING: return '决策中';
      case RepairStatus.EXTERNAL_REPAIR: return '外部维修';
      case RepairStatus.INTERNAL_REPAIR: return '内部维修';
      case RepairStatus.WAITING_FOR_APPROVAL: return '等待审批';
      case RepairStatus.APPROVED: return '已审批';
      case RepairStatus.IN_PROGRESS: return '进行中';
      case RepairStatus.WAITING_FOR_PARTS: return '等待备件';
      case RepairStatus.TESTING: return '测试中';
      case RepairStatus.COMPLETED: return '已完成';
      case RepairStatus.REJECTED: return '已拒绝';
      case RepairStatus.CANCELLED: return '已取消';
      default: return '未知';
    }
  }

  getWorkflowStepText(step: string): string {
    switch (step) {
      case 'Start': return '开始';
      case 'DecisionPending': return '决策中';
      case 'ExternalVendorForm': return '外部厂商表单';
      case 'InternalRepairForm': return '内部维修表单';
      case 'RepairDetailsForm': return '维修详情表单';
      case 'ApprovalPending': return '等待审批';
      case 'DecisionReview': return '决策复审';
      case 'Completed': return '已完成';
      default: return step;
    }
  }
} 